#include "imagelabel.h"

ImageLabel::ImageLabel(QWidget *parent) : QLabel(parent) {
    setScaledContents(true);
}

void ImageLabel::setPixmapWithScale(const QPixmap& pixmap, float& scaleOut) {
    originalPixmap = pixmap;
    QSize canvasSize = size();
    QSize scaledSize = pixmap.size();
    scaledSize.scale(canvasSize, Qt::KeepAspectRatio);
    scaleOut = static_cast<float>(scaledSize.width()) / pixmap.width();
    setPixmap(pixmap.scaled(scaledSize, Qt::KeepAspectRatio));
}

void ImageLabel::mousePressEvent(QMouseEvent* event) {
    startPos = event->pos();
    selecting = true;
    update();
}

void ImageLabel::mouseMoveEvent(QMouseEvent* event) {
    if (selecting) {
        endPos = event->pos();
        update();
    }
}

void ImageLabel::mouseReleaseEvent(QMouseEvent* event) {
    selecting = false;
    endPos = event->pos();
    QRect rect = QRect(startPos, endPos).normalized();
    emit regionSelected(rect);
    update();
}

void ImageLabel::paintEvent(QPaintEvent* event) {
    QLabel::paintEvent(event);
    if (selecting) {
        QPainter painter(this);
        painter.setPen(QPen(Qt::red, 2));
        painter.drawRect(QRect(startPos, endPos).normalized());
    }
}
